import { Injectable } from '@nestjs/common';
import { AuthDao as Dao } from '@/servers/daos/auth/auth.dao';
import { InwuAuthService } from '@/servers/api/inwu/auth/inwu-auth.service';
import { CacheService } from '@/servers/redis/cache/cache.service';
import { UserinfoService } from '@/servers/redis/userinfo/userinfo.service';

@Injectable()
export class AuthService {


    constructor(
        private inwuAuthService: InwuAuthService,
        private cacheService: CacheService,
        private userinfoService: UserinfoService,
        private dao: Dao
    ) { }

    /**
     * 验证登录
     */
    async login(params: any, req: any): Promise<any> {
        let permission = null, inwu_auth = null, inwu_user = null, message = '', token = null, areas = [];
        //获取用户信息
        const user = await this.dao.getUser(params);
        if (user.length > 0) {

            //判断是否超级管理员
            if (user[0].username === 'admin') {
                //获取所有权限
                permission = await this.dao.getAdminPermission();
                //如果是admin超级管理员，则使用8080服务器分配的租户用户名和密码，可以实现配置这个用户和密码
                params.username = 'admin';
                params.password = '123456';
            } else {
                //获取用户权限
                permission = await this.dao.findUserPermission({ id: user[0].id });
            }

            //登录inwu平台
            inwu_auth = await this.inwuAuthService.login(params).then(res => {
                return {
                    //thingsboard平台状态刷新refreshToken
                    refreshToken: res.refreshToken,
                    //thingsboard平台状态刷新token
                    token: res.token,
                };
            }, err => {
                return err;
            });
            //返回inwu平台的用户信息
            if (inwu_auth) {
                inwu_user = await this.inwuAuthService.getUser({}, inwu_auth.token);
            }

            token = 'token' + params.username + Math.random() * 1000;
            let data = {
                base: {
                    //用户信息
                    userinfo: {
                        id: user[0].id,
                        business_id: user[0].business_id,
                        nickname: user[0].nickname,
                        username: user[0].username,
                        telphone: user[0].telphone
                    },
                    //用户权限
                    permission: permission,
                    //区域
                    areas: areas
                },
                inwu: {
                    //thingsboard平台状态刷新refreshToken
                    refreshToken: inwu_auth.refreshToken,
                    //thingsboard平台状态刷新token
                    token: inwu_auth.token,
                    //thingsboard用户信息
                    userinfo: inwu_user
                },
                //本平台的token
                token: token,
                //提示
                message: ''
            }
            req.session.token = token;
            req.session.cookie.maxAge = 1000 * 60 * 60 * 2;
            this.cacheService.set(token, data);
            return data;
        } else {
            return '用户不存在';
        }
    }

    /**
     * 
     * @param token 退出登录
     */
    async logout(token: string) {
        const inwu_token = await this.userinfoService.getInwuToken(token);
        const inwu_res = await this.inwuAuthService.logout({}, inwu_token);
        const res = await this.cacheService.delete(token);
        if (inwu_res == 200 && res == 1) {
            return res;
        } else {
            if(res == 1){
                return 2;
            }else{
                return 3;
            }
        }

    }

    /**
     * 获取个人信息
     * @param params 
     */
    getUser(params: any): Promise<any[]> {
        return this.dao.getUser(params);
    }

    /**
     * 刷新token
     * @param params 
     */
    async refreshToken(params: any) {
        //通过token获取用户
        let user = await this.userinfoService.getUser(params.authorization);
        //通过refreshToken去刷新token
        let res = await this.inwuAuthService.refreshToken({ refreshToken: user.inwu.refreshToken });
        //修改本地token
        user.inwu.token = res.token;
        //修改本地refreshToken
        user.inwu.refreshToken = res.refreshToken;
        //把修改后的用户信息保存到缓存中
        this.cacheService.set(params.authorization, user);
        return res;
    }

}
